package com.csnj.admin.controller.SystemManager;

import com.csnj.common.annotation.ApiNeedLog;
import com.csnj.common.annotation.ModelName;
import com.csnj.common.constant.CommonConstants;
import com.csnj.common.entity.APIResult;
import com.csnj.common.exception.IRCException;
import com.csnj.common.jwt.JwtAuthenticationRequest;
import com.csnj.common.jwt.JwtInfo;
import com.csnj.common.utils.BaseContextHandler;
import com.csnj.common.utils.IpUtil;
import com.csnj.core.Srvs.SysManager.AuthSrvs;
import com.csnj.core.exception.TokenInvalidException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("auth")
@Log4j2
@ModelName(ModelName = "认证")
public class AuthController {
    @Value("${jwt.token-header}")
    private String tokenHeader;
    @Autowired
    private AuthSrvs authService;

    @RequestMapping(value = "token", method = RequestMethod.POST)
    @ApiNeedLog(desc = "系统登录")
    public APIResult createAuthenticationToken(
            @RequestBody JwtAuthenticationRequest authenticationRequest, HttpServletRequest request) {

        String token="";
        try {
            token = authService.validate(authenticationRequest);
        } catch (IRCException e) {
            return new APIResult(e);
        }
        request.getSession().setAttribute(CommonConstants.CONTEXT_KEY_USER_ID, BaseContextHandler.getUserID());
        request.getSession().setAttribute(CommonConstants.CONTEXT_KEY_USER_NAME, BaseContextHandler.getUsername());

        authService.SaveLoginLog(BaseContextHandler.getUserID(), IpUtil.getIp(request));
        return new APIResult(token);
    }

    @RequestMapping(value = "refresh", method = RequestMethod.GET)
    public APIResult refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws Exception {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        return new APIResult(refreshedToken);
    }

    @RequestMapping(value = "verify", method = RequestMethod.GET)
    public APIResult verify(String token, HttpServletRequest request){
        JwtInfo info = null;
        try {
            info = authService.validate(token);
        } catch (TokenInvalidException e) {
            return new APIResult(e);
        }
        request.getSession().setAttribute("uid", info.getUserId());
        request.getSession().setAttribute("name", info.getUsername());
        return new APIResult(info);
    }
}
